package jehc.cloud.gen.service.generator;

import jehc.cloud.common.util.ExceptionUtil;
import jehc.cloud.gen.model.XtGenerator;
import jehc.cloud.gen.model.XtGeneratorGridColumn;
import jehc.cloud.gen.model.XtGeneratorSearchFiled;
import jehc.cloud.gen.model.XtGeneratorTableColumn;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
 * @Desc bootstrap风格方式生成列表生成
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Slf4j
public class GeneratorBootPageList extends GeneratorUtil {
	/**
	 * 生成列表Html及列表JS
	 * @param xtGeneratorTableColumnList
	 * @param xtGenerator
	 */
	public void createPageAll(List<XtGeneratorTableColumn> xtGeneratorTableColumnList, XtGenerator xtGenerator){
		createPageBootListJs(xtGeneratorTableColumnList, xtGenerator);
		createPageBootListHtml(xtGeneratorTableColumnList, xtGenerator);
	}
	
	//////////////////////1创建bootstrap 列表//////////////////////////
	/**
	 * 1.1.1生成bootstrap页面----list.JS
	 * 
	 * @param xtGeneratorTableColumnList
	 * @param xtGenerator
	 * @return
	 */
	public String createPageBootListJs(List<XtGeneratorTableColumn> xtGeneratorTableColumnList,XtGenerator xtGenerator) {
		StringBuffer sb = new StringBuffer();
		sb.append(createPageBootListJsContent(xtGeneratorTableColumnList, xtGenerator));
		String path = xtGenerator.getXt_generator_path();
		OutputStreamWriter out = null;
		try {
			out = new OutputStreamWriter(new FileOutputStream(path + lowAllChar_(xtGenerator.getXt_generator_tbname()) + "-list.js"),"UTF-8");
			try {
				out.write(sb.toString());
			} catch (IOException e) {
				log.error(e.getMessage());
				throw new ExceptionUtil(e.getMessage(), e.getCause());
			}
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage());
			throw new ExceptionUtil(e.getMessage(), e.getCause());
		} catch (FileNotFoundException e) {
			log.error(e.getMessage());
			throw new ExceptionUtil(e.getMessage(), e.getCause());
		} finally {
			try {
				out.flush();
				out.close();
			} catch (IOException e) {
				log.error(e.getMessage());
				throw new ExceptionUtil(e.getMessage(), e.getCause());
			}
		}
		return sb.toString();
	}

	
	/**
	 * 1.1.2创建列表JS内容区域
	 * @param xtGeneratorTableColumnList
	 * @param xtGenerator
	 * @return
	 */
	public String createPageBootListJsContent(List<XtGeneratorTableColumn> xtGeneratorTableColumnList,XtGenerator xtGenerator) {
		StringBuffer sb = new StringBuffer();
		String root_url = lowOneCharAll_(xtGenerator.getXt_generator_tbname());
		sb.append("var grid;\r\n");
		sb.append("$(document).ready(function() {\r\n");
		sb.append("\t/////////////jehc扩展属性目的可方便使用（boot.js文件datatablesCallBack方法使用） 如弹窗分页查找根据条件 可能此时的form发生变化 此时 可以解决该类问题\r\n");
		sb.append("\tvar opt = {\r\n");
		sb.append("\t\tsearchformId:'searchForm'\r\n");
		sb.append("\t};\r\n");
		
		sb.append("\tvar options = DataTablesPaging.pagingOptions({\r\n");
		sb.append("\t\tajax:function (data, callback, settings){datatablesCallBack(data, callback, settings,"+xtGenerator.getRest_url_prefix()+"+'/"+root_url+"/list',opt);},//渲染数据\r\n");
		sb.append("\t\t\t//在第一位置追加序列号\r\n");
		sb.append("\t\t\tfnRowCallback:function(nRow, aData, iDisplayIndex){\r\n");
		sb.append("\t\t\t\tjQuery('td:eq(1)', nRow).html(iDisplayIndex +1);  \r\n");
		sb.append("\t\t\t\treturn nRow;\r\n");
		sb.append("\t\t},\r\n");
		
		sb.append("\t\torder:[],//取消默认排序查询,否则复选框一列会出现小箭头\r\n");
		sb.append("\t\ttableHeight:reGetBodyHeight()*0.55+'px',\r\n");
		sb.append("\t\t//列表表头字段\r\n");
		sb.append("\t\tcolums:[\r\n");
		//字段显示开始
		sb.append("\t\t\t{\r\n");
		sb.append("\t\t\t\tsClass:\"text-center\",\r\n");
		sb.append("\t\t\t\twidth:\"50px\",\r\n");
		sb.append("\t\t\t\tdata:\""+getColumnKey(xtGeneratorTableColumnList)+"\",\r\n");
		sb.append("\t\t\t\trender:function (data, type, full, meta) {\r\n");
		sb.append("\t\t\t\t\treturn '<label class=\"mt-checkbox mt-checkbox-single mt-checkbox-outline\"><input type=\"checkbox\" name=\"checkId\" class=\"checkchild \" value=\"' + data + '\" /><span></span></label>';\r\n");
		sb.append("\t\t\t\t},\r\n");
		sb.append("\t\t\t\tbSortable:false\r\n");
		sb.append("\t\t\t},\r\n");
		//序号
		sb.append("\t\t\t{\r\n");
		sb.append("\t\t\t\tdata:\""+getColumnKey(xtGeneratorTableColumnList)+"\",\r\n");
		sb.append("\t\t\t\twidth:\"50px\"\r\n");
		sb.append("\t\t\t},\r\n");
		
		List<XtGeneratorGridColumn> xtGeneratorGridColumnList = xtGenerator.getXt_Generator_Grid_ColumnList();
		for(int i = 0; i < xtGeneratorGridColumnList.size(); i++){
			XtGeneratorGridColumn xtGeneratorGridColumn = xtGeneratorGridColumnList.get(i);
			sb.append("\t\t\t{\r\n");
			sb.append("\t\t\t\tdata:'"+xtGeneratorGridColumn.getXt_generator_grid_column_name()+"'\r\n");
			sb.append("\t\t\t},\r\n");
		}
		sb.append("\t\t\t{\r\n");
		sb.append("\t\t\t\tdata:\""+getColumnKey(xtGeneratorTableColumnList)+"\",\r\n");
		sb.append("\t\t\t\twidth:\"150px\",\r\n");
		sb.append("\t\t\t\trender:function(data, type, row, meta) {\r\n");
		sb.append("\t\t\t\t\treturn \"<button class='m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill' onclick=\\\"javascript:to"+uprepchar(xtGenerator.getXt_generator_tbname())+"Detail('\"+ data +\"')\\\"><i class='la la-eye'></i></button>\";\r\n");
		sb.append("\t\t\t\t}\r\n");
		sb.append("\t\t\t}\r\n");
		//字段显示结束
		sb.append("\t\t]\r\n");
		sb.append("\t});\r\n");
		sb.append("\tgrid=$('#datatables').dataTable(options);\r\n");
		sb.append("\t//实现全选反选\r\n");
		sb.append("\tdocheckboxall('checkall','checkchild');\r\n");
		sb.append("\t//实现单击行选中\r\n");
		sb.append("\tclickrowselected('datatables');\r\n");
		sb.append("});\r\n");
		
		//追加新增方法
		sb.append("//新增\r\n");
		sb.append("function to"+uprepchar(xtGenerator.getXt_generator_tbname())+"Add(){\r\n");
		sb.append("\ttlocation(base_html_redirect+'/"+xtGenerator.getXt_generator_page_package()+"/"+lowAllChar_(xtGenerator.getXt_generator_tbname())+"/"+lowAllChar_(xtGenerator.getXt_generator_tbname())+"-add"+".html');\r\n");
		sb.append("}\r\n");
		
		//追加修改方法
		sb.append("//修改\r\n");
		sb.append("function to"+uprepchar(xtGenerator.getXt_generator_tbname())+"Update(){\r\n");
		sb.append("\tif($(\".checkchild:checked\").length != 1){\r\n");
		sb.append("\t\ttoastrBoot(4,\"选择数据非法\");\r\n");
		sb.append("\t\treturn;\r\n");
		sb.append("\t}\r\n");
		sb.append("\tvar id = $(\".checkchild:checked\").val();\r\n");
		sb.append("\ttlocation(base_html_redirect+'/"+xtGenerator.getXt_generator_page_package()+"/"+lowAllChar_(xtGenerator.getXt_generator_tbname())+"/"+lowAllChar_(xtGenerator.getXt_generator_tbname())+"-update"+".html?"+getColumnKey(xtGeneratorTableColumnList)+"='+id);\r\n");
		sb.append("}\r\n");
		
		//追加详细方法
		sb.append("//详情\r\n");
		sb.append("function to"+uprepchar(xtGenerator.getXt_generator_tbname())+"Detail(id){\r\n");
		sb.append("\ttlocation(base_html_redirect+'/"+xtGenerator.getXt_generator_page_package()+"/"+lowAllChar_(xtGenerator.getXt_generator_tbname())+"/"+lowAllChar_(xtGenerator.getXt_generator_tbname())+"-detail"+".html?"+getColumnKey(xtGeneratorTableColumnList)+"='+id);\r\n");
		sb.append("}\r\n");
		
		//追加删除方法
		sb.append("//删除\r\n");
		sb.append("function del"+uprepchar(xtGenerator.getXt_generator_tbname())+"(){\r\n");
		sb.append("\tif(returncheckedLength('checkchild') <= 0){\r\n");
		sb.append("\t\ttoastrBoot(4,\"请选择要删除的数据\");\r\n");
		sb.append("\t\treturn;\r\n");
		sb.append("\t}\r\n");
		sb.append("\tmsgTishCallFnBoot(\"确定要删除所选择的数据？\",function(){\r\n");
		sb.append("\t\tvar id = returncheckIds('checkId').join(\",\");\r\n");
		sb.append("\t\tvar params = {"+getColumnKey(xtGeneratorTableColumnList)+":id,_method:'DELETE'};\r\n");
		sb.append("\t\tajaxBReq("+xtGenerator.getRest_url_prefix()+"+'/"+root_url+"/delete',params,['datatables'],null,\"DELETE\");\r\n");
		sb.append("\t})\r\n");
		sb.append("}\r\n");
		
		//追加初始化日历选择器（需要做判断 判断查询条件中存在日期类型）
		boolean existDateType = false;
		List<XtGeneratorSearchFiled> xtGeneratorSearchFileds = xtGenerator.getXt_generator_search_filedList();
		for(XtGeneratorSearchFiled xtGeneratorSearchFiled:xtGeneratorSearchFileds){
			if("4".equals(xtGeneratorSearchFiled.getXt_generator_search_type())){
				existDateType = true;
				break;
			}
		}
		if(existDateType){
			sb.append("//初始化日期选择器\r\n");
			sb.append("$(document).ready(function(){\r\n");
			sb.append("\tdatetimeInit();\r\n");
			sb.append("});\r\n");
		}
		return sb.toString();
	}
	
	
	
	
	/**
	 * 1.2.1生成bootstrap页面----list.html
	 * 
	 * @param xtGeneratorTableColumnList
	 * @param xtGenerator
	 * @return
	 */
	public String createPageBootListHtml(List<XtGeneratorTableColumn> xtGeneratorTableColumnList,XtGenerator xtGenerator) {
		StringBuffer sb = new StringBuffer();
		sb.append(createPageBootListHtmlContent(xtGeneratorTableColumnList, xtGenerator));
		String path = xtGenerator.getXt_generator_path();
		OutputStreamWriter out = null;
		try {
			out = new OutputStreamWriter(new FileOutputStream(path + lowAllChar_(xtGenerator.getXt_generator_tbname()) + "-list.html"),"UTF-8");
			try {
				out.write(sb.toString());
			} catch (IOException e) {
				log.error(e.getMessage());
				throw new ExceptionUtil(e.getMessage(), e.getCause());
			}
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage());
			throw new ExceptionUtil(e.getMessage(), e.getCause());
		} catch (FileNotFoundException e) {
			log.error(e.getMessage());
			throw new ExceptionUtil(e.getMessage(), e.getCause());
		} finally {
			try {
				out.flush();
				out.close();
			} catch (IOException e) {
				log.error(e.getMessage());
				throw new ExceptionUtil(e.getMessage(), e.getCause());
			}
		}
		return sb.toString();
	}

	
	/**
	 * 1.2.2创建列表html内容区域
	 * @param xtGeneratorTableColumnList
	 * @param xtGenerator
	 * @return
	 */
	public String createPageBootListHtmlContent(List<XtGeneratorTableColumn> xtGeneratorTableColumnList,XtGenerator xtGenerator) {
		StringBuffer sb = new StringBuffer();
		String root_url = lowOneCharAll_(xtGenerator.getXt_generator_tbname());
		String list_url = "get"+uprepchar(xtGenerator.getXt_generator_tbname())+"ListByCondition";
		List<XtGeneratorSearchFiled> xtGeneratorSearchFileds = xtGenerator.getXt_generator_search_filedList();
		List<String> xt_script_idList = new ArrayList<String>();
		for(int i = 0; i < xtGeneratorSearchFileds.size(); i++){
			XtGeneratorSearchFiled xtGeneratorSearchFiled = xtGeneratorSearchFileds.get(i);
			String xt_script_id = xtGeneratorSearchFiled.getXt_script_id();
			if(null != xt_script_id && !"".equals(xt_script_id)){
				xt_script_idList.add(xt_script_id);
			}
		}
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n");
		sb.append("<!DOCTYPE html SYSTEM \"http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd\">\r\n");
		sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:th=\"http://www.thymeleaf.org\">\r\n");
		sb.append("<head>\r\n");
		sb.append("<meta charset=\"UTF-8\">\r\n");
		sb.append("<script type=\"text/javascript\" src=\"/deng/include/include-css.js\"></script>\r\n");
		sb.append("<title>"+xtGenerator.getXt_generator_tbcomment()+"</title>\r\n");
		sb.append("</head>\r\n");
		
		sb.append("<body>\r\n");
		//查询开始
		sb.append("\t<div class=\"m-content\">\r\n");
		sb.append("\t\t<div class=\"m-portlet\">\r\n");
		sb.append("\t\t\t<div class=\"m-portlet__head\">\r\n");
		sb.append("\t\t\t\t<div class=\"m-portlet__head-caption\">\r\n");
		sb.append("\t\t\t\t\t<div class=\"m-portlet__head-title\">\r\n");
		sb.append("\t\t\t\t\t\t<h3 class=\"m-portlet__head-text\">\r\n");
		sb.append("\t\t\t\t\t\t\t<span class=\"m-accordion__item-icon\"><i class=\"flaticon-search\"></i>查询区域</span>\r\n");
		sb.append("\t\t\t\t\t\t</h3>\r\n");
		sb.append("\t\t\t\t\t</div>\r\n");
		sb.append("\t\t\t\t</div>\r\n");
		sb.append("\t\t\t</div>\r\n");
		
		/**表单设计开始**/
		sb.append("\t\t\t<form class=\"m-form m-form--fit m-form--label-align-left m-form--group-seperator-dashed\" method=\"POST\" id=\"searchForm\">\r\n");
		//内容模块
		sb.append("\t\t\t\t<div class=\"m-portlet__body\">\r\n");
		//查询区域内容开始
		sb.append("\t\t\t\t\t<div class=\"form-group m-form__group row\">\r\n");
		for(int i = 0; i < xtGeneratorSearchFileds.size(); i++){
			XtGeneratorSearchFiled xtGeneratorSearchFiled = xtGeneratorSearchFileds.get(i);
			String xt_generator_search_name = xtGeneratorSearchFiled.getXt_generator_search_name();
			String xt_generator_search_label = xtGeneratorSearchFiled.getXt_generator_search_label();
			String xt_generator_search_type = xtGeneratorSearchFiled.getXt_generator_search_type();
			String xtype="textfield";
			if("0".equals(xt_generator_search_type)){
				xtype="textfield";
			}else if("1".equals(xt_generator_search_type)){
				xtype="textareafield";
			}else if("2".equals(xt_generator_search_type)){
				xtype="numberfield";
			}else if("3".equals(xt_generator_search_type)){
				xtype="combo";
			}else if("4".equals(xt_generator_search_type)){
				xtype="datefield";
			}
//			sb.append("\t\t\t\t\t<div class=\"form-group m-form__group row\">\r\n");
			sb.append("\t\t\t\t\t\t<label class=\"col-form-label\">"+xt_generator_search_label+"</label>\r\n");
			sb.append("\t\t\t\t\t\t<div class=\"col-lg-2\">\r\n");
			if("0".equals(xt_generator_search_type) || "2".equals(xt_generator_search_type)){
				sb.append("\t\t\t\t\t\t\t\t<input type=\"text\" class=\"form-control\" name=\""+xt_generator_search_name+"\" placeholder=\"请输入"+xt_generator_search_label+"\">\r\n");
			}else if("1".equals(xt_generator_search_type)){
				sb.append("\t\t\t\t\t\t\t<textarea class=\"form-control\" name=\""+xt_generator_search_name+"\" placeholder=\"请输入"+xt_generator_search_label+"\"></textarea>\r\n");
			}else if("3".equals(xt_generator_search_type)){
				sb.append("\t\t\t\t\t\t\t<select class=\"form-control\" name=\""+xt_generator_search_name+"\" placeholder=\"请选择\"></select>\r\n");
			}else if("4".equals(xt_generator_search_type)){
				sb.append("\t\t\t\t\t\t\t<div class=\"input-group\">\r\n");
				sb.append("\t\t\t\t\t\t\t\t<input type=\"text\" class=\"form_datetime form-control\" placeholder=\"起始时间\" name=\""+xt_generator_search_name+"_st\" />\r\n");
				sb.append("\t\t\t\t\t\t\t\t<label class=\"col-form-label\">至</label>\r\n");
				sb.append("\t\t\t\t\t\t\t\t<input type=\"text\" class=\"form_datetime form-control\" placeholder=\"结束时间\" name=\""+xt_generator_search_name+"_et\" />\r\n");
				sb.append("\t\t\t\t\t\t\t</div>\r\n");
			}
			sb.append("\t\t\t\t\t\t</div>\r\n");
//			sb.append("\t\t\t\t\t</div>\r\n");
		}
		sb.append("\t\t\t\t\t</div>\r\n");
		sb.append("\t\t\t\t</div>\r\n");
		sb.append("\t\t\t\t<div class=\"m-portlet__foot m-portlet__no-border m-portlet__foot--fit\">\r\n");
		sb.append("\t\t\t\t\t<div class=\"m-form__actions m-form__actions--solid\">\r\n");
		sb.append("\t\t\t\t\t\t<div class=\"row\">\r\n");
		//按钮开始

		sb.append("\t\t\t\t\t\t\t<div class=\"col m--align-left\">\r\n");
		sb.append("\t\t\t\t\t\t\t\t<a href=\"javascript:search('datatables')\" class=\"btn btn-accent m-btn m-btn--icon m-btn--wide\">\r\n");
		sb.append("\t\t\t\t\t\t\t\t\t<span><i class=\"fa fa-search\"></i><span>检索</span></span>\r\n");
		sb.append("\t\t\t\t\t\t\t\t</a>\r\n");
		sb.append("\t\t\t\t\t\t\t\t<a href=\"javascript:resetAll()\" class=\"btn btn-secondary m-btn m-btn--custom m-btn--icon\">\r\n");
		sb.append("\t\t\t\t\t\t\t\t\t<span><i class=\"fa fa-repeat\"></i><span>清空条件</span></span>\r\n");
		sb.append("\t\t\t\t\t\t\t\t</a>\r\n");
		sb.append("\t\t\t\t\t\t\t</div>\r\n");

		sb.append("\t\t\t\t\t\t\t<div class=\"col m--align-right\">\r\n");
		sb.append("\t\t\t\t\t\t\t\t<a class=\"btn btn-secondary m-btn m-btn--custom m-btn--label-success\" href=\"javascript:to"+uprepchar(xtGenerator.getXt_generator_tbname())+"Add()\">\r\n");
		sb.append("\t\t\t\t\t\t\t\t\t<span><i class=\"la la-plus la-lg\"></i><span>新增</span></span>\r\n");
		sb.append("\t\t\t\t\t\t\t\t</a>\r\n");
		sb.append("\t\t\t\t\t\t\t\t<a class=\"btn btn-secondary m-btn m-btn--custom m-btn--label-primary\" href=\"javascript:to"+uprepchar(xtGenerator.getXt_generator_tbname())+"Update()\">\r\n");
		sb.append("\t\t\t\t\t\t\t\t\t<span><i class=\"fa fa-magic fa-lg\"></i><span>修改</span></span>\r\n");
		sb.append("\t\t\t\t\t\t\t\t</a>\r\n");
		sb.append("\t\t\t\t\t\t\t\t<a class=\"btn btn-secondary m-btn m-btn--custom m-btn--label-danger m-btn--bolder m-btn--uppercase\" href=\"javascript:del"+uprepchar(xtGenerator.getXt_generator_tbname())+"()\">\r\n");
		sb.append("\t\t\t\t\t\t\t\t\t<span><i class=\"fa fa-times\"></i><span>删除</span></span>\r\n");
		sb.append("\t\t\t\t\t\t\t\t</a>\r\n");
		sb.append("\t\t\t\t\t\t\t\t<a class=\"btn btn-secondary m-btn m-btn--custom m-btn--label-warning m-btn--bolder m-btn--uppercase\" href=\"javascript:search('datatables')\">\r\n");
		sb.append("\t\t\t\t\t\t\t\t\t<span><i class=\"fa fa-spin fa-refresh m-r-5\"></i><span>刷新</span></span>\r\n");
		sb.append("\t\t\t\t\t\t\t\t</a>\r\n");
		sb.append("\t\t\t\t\t\t\t</div>\r\n");
		

		//按钮结束
		sb.append("\t\t\t\t\t\t</div>\r\n");
		sb.append("\t\t\t\t\t</div>\r\n");
		sb.append("\t\t\t\t</div>\r\n");
		/**表单设计结束**/
		sb.append("\t\t\t</form>\r\n");
		sb.append("\t\t</div>\r\n");
		//查询区域内容结束
		
		/////////////////////////内容开始////////////////////////
		sb.append("\t\t<table id=\"datatables\" class=\"table table-bordered table-striped table-hover\" style=\"white-space: nowrap; width: 99.9%\">\r\n");
		sb.append("\t\t\t<thead>\r\n");
		sb.append("\t\t\t\t<tr>\r\n");
		sb.append("\t\t\t\t\t<th><label class=\"mt-checkbox mt-checkbox-single mt-checkbox-outline\"><input type=\"checkbox\" class=\"checkall\" /><span></span></label></th>\r\n");//复选框
		sb.append("\t\t\t\t\t<th>序号</th>\r\n");//序号
		//遍历字段开始
		List<XtGeneratorGridColumn> xtGeneratorGridColumnList = xtGenerator.getXt_Generator_Grid_ColumnList();
		for(int i = 0; i < xtGeneratorGridColumnList.size(); i++){
			XtGeneratorGridColumn xtGeneratorGridColumn = xtGeneratorGridColumnList.get(i);
			sb.append("\t\t\t\t\t<th>"+xtGeneratorGridColumn.getXt_generator_grid_column_label()+"</th>\r\n");
		}
		//遍历字段结束
		sb.append("\t\t\t\t\t<th>操作</th>\r\n");
		sb.append("\t\t\t\t</tr>\r\n");
		sb.append("\t\t\t</thead>\r\n");
		sb.append("\t\t</table>\r\n");
		sb.append("\t</div>\r\n");
		
		sb.append("</body>\r\n");
		//导入JS支持
		sb.append("<script type=\"text/javascript\" src=\"/deng/include/include.js\"></script>\r\n");
		sb.append("<script type=\"text/javascript\" src=\"/deng/view/"+xtGenerator.getXt_generator_page_package()+"/"+lowAllChar_(xtGenerator.getXt_generator_tbname())+"/"+lowAllChar_(xtGenerator.getXt_generator_tbname())+"-list.js\"></script> \r\n");
		sb.append("</html>\r\n");
		/////////////////////////内容结束////////////////////////
		return sb.toString();
	}
}
